package com.arunsawad.ilertu.activity;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;

import com.arunsawad.ilertu.R;
import com.arunsawad.ilertu.adapter.CategoriesAdapter;
import com.arunsawad.ilertu.common.AsyncActivity;
import com.arunsawad.ilertu.common.Constants;
import com.arunsawad.ilertu.common.RequestTask;
import com.arunsawad.ilertu.common.Validator;
import com.arunsawad.ilertu.dto.Category;

public class Categories extends Activity implements AsyncActivity {
	SharedPreferences preferences;
	GridView listView;
	private List<Category> categories = new ArrayList<Category>();
	private CategoriesAdapter adapter;
	ProgressDialog bar;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.act_categories);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.title1_imgbtn_txt_imgbtn);

		initTitle();

		preferences = getSharedPreferences(Constants.PREF_FILE, MODE_PRIVATE);
		Validator.Validate(this, preferences);
		initTitle();
		// Getting a reference to ListView
		listView = (GridView) findViewById(R.id.gv_categories);
		LoadContent();
	}

	@SuppressWarnings("deprecation")
	public void initTitle() {
		ImageButton imgBtn1 = (ImageButton) findViewById(R.id.title1_imgBtn1);
		imgBtn1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), Home.class);
				startActivity(intent);
			}
		});

		TextView txtTitle = (TextView) findViewById(R.id.title1_txtTitle);
		txtTitle.setText(getString(R.string.categories));

		ImageButton imgBtn2 = (ImageButton) findViewById(R.id.title1_imgBtn2);
		imgBtn2.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.services));
		imgBtn2.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),
						Services.class);
				startActivity(intent);
			}
		});
	}

	public void LoadContent() {
		// show progress bar
		bar = new ProgressDialog(Categories.this);
		bar.setIndeterminate(true);
		bar.show();

		String msg = String.format(Constants.MSG,
				"ilertu.service-categories-list",
				preferences.getString(Constants.PREF_USER_NAME, ""),
				preferences.getString(Constants.PREF_PASSWORD, ""),
				preferences.getString(Constants.PREF_LANGUAGE, "en"), "");

		RequestTask task = new RequestTask();
		task.setListener(this);
		task.execute(Constants.URL_GET_CATEGORIES, msg);
	}

	@Override
	public void onRequestCompleted(String results) {
		if (results != null) {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder;
			try {
				builder = factory.newDocumentBuilder();
				Document document = builder.parse(new InputSource(
						new StringReader(results)));
				NodeList nodes = document
						.getElementsByTagName("serviceCategory");

				// fill in the list items from the XML document
				for (int i = 0; i < nodes.getLength(); i++) {
					Element e = (Element) nodes.item(i);

					int id = Integer.parseInt(e.getAttribute("id"));
					String name = e.getElementsByTagName("name").item(0)
							.getTextContent();
					String imageUrl = e.getElementsByTagName("imageUrl")
							.item(0).getTextContent();
					Category service = new Category(id, name, imageUrl);
					categories.add(service);
				}

				// create base adapter
				adapter = new CategoriesAdapter(Categories.this, categories);
				listView.setAdapter(adapter);

				// hide progress bar
				bar.hide();

				// star loading image for each service
				for (Category c : categories) {
					c.loadImage(adapter);
				}

				listView.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						TextView txtCategoryId = (TextView) view
								.findViewById(R.id.categories_txtCategoryId);
						Intent intent = new Intent(getApplicationContext(),
								Services.class);
						intent.putExtra("categoryId", txtCategoryId.getText());
						startActivity(intent);
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}